from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.pagination import PageNumberPagination
from django.shortcuts import get_object_or_404
from django.db.models import Q, Count
from django.utils import timezone
from datetime import timedelta
import requests
from .models import Story
from .serializers import (
    StoryListSerializer,
    StoryDetailSerializer,
    StoryCreateSerializer,
    StoryGenerateSerializer
)
from accounts.models import User


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def generate_story(request):
    """AI生成故事"""
    serializer = StoryGenerateSerializer(data=request.data)
    
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '参数验证失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    prompt = serializer.validated_data['prompt']
    category = serializer.validated_data['category']
    word_count = serializer.validated_data['word_count']
    
    try:
        # 调用Pollinations AI API
        api_prompt = f"写一个关于{prompt}的{word_count}字{category}类型中文故事"
        api_url = f"https://text.pollinations.ai/{api_prompt}"
        
        response = requests.get(api_url, timeout=30)
        response.raise_for_status()
        
        ai_content = response.text.strip()
        
        # 生成标题
        title_templates = {
            '奇幻': f"{prompt}的奇幻冒险",
            '科幻': f"{prompt}星际纪元",
            '爱情': f"遇见{prompt}",
            '悬疑': f"{prompt}之谜",
            '冒险': f"{prompt}大冒险",
            '恐怖': f"{prompt}的恐怖夜晚",
            '历史': f"{prompt}传奇",
            '现代': f"现代{prompt}",
            '武侠': f"{prompt}江湖录",
            '仙侠': f"{prompt}修仙记",
        }
        title = title_templates.get(category, f"{prompt}的故事")
        
        # 创建故事
        story = Story.objects.create(
            title=title,
            content=ai_content,
            category=category,
            author=request.user,
            status='draft',
            tags=[prompt, category, 'AI生成']
        )
        
        story_data = StoryDetailSerializer(story, context={'request': request}).data
        
        return Response({
            'success': True,
            'message': '故事生成成功！已保存为草稿',
            'data': story_data
        }, status=status.HTTP_201_CREATED)
    
    except requests.RequestException as e:
        return Response({
            'success': False,
            'message': f'AI服务暂时不可用，请稍后重试'
        }, status=status.HTTP_503_SERVICE_UNAVAILABLE)
    except Exception as e:
        return Response({
            'success': False,
            'message': f'故事生成失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def story_list(request):
    """获取故事列表"""
    stories = Story.objects.select_related('author').prefetch_related('comments')
    
    # 过滤参数
    category = request.GET.get('category')
    status_filter = request.GET.get('status')
    author_id = request.GET.get('author_id')
    search = request.GET.get('search')
    
    # 只有登录用户可以看到自己的草稿
    if request.user.is_authenticated:
        stories = stories.filter(
            Q(status='published') | Q(author=request.user)
        )
    else:
        stories = stories.filter(status='published')
    
    # 应用过滤条件
    if category:
        stories = stories.filter(category=category)
    if status_filter:
        stories = stories.filter(status=status_filter)
    if author_id:
        stories = stories.filter(author_id=author_id)
    if search:
        stories = stories.filter(
            Q(title__icontains=search) | Q(content__icontains=search)
        )
    
    # 排序
    sort_by = request.GET.get('sort', 'latest')
    if sort_by == 'popular':
        stories = stories.order_by('-likes', '-views')
    elif sort_by == 'views':
        stories = stories.order_by('-views')
    else:  # latest
        stories = stories.order_by('-created_at')
    
    # 分页
    paginator = PageNumberPagination()
    page_size = request.GET.get('page_size', 20)
    paginator.page_size = int(page_size)
    page = paginator.paginate_queryset(stories, request)
    
    serializer = StoryListSerializer(page, many=True, context={'request': request})
    
    return paginator.get_paginated_response({
        'success': True,
        'data': {
            'items': serializer.data,
            'total': stories.count()
        }
    })


@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def story_detail(request, story_id):
    """获取故事详情"""
    story = get_object_or_404(Story, id=story_id)
    
    # 权限检查：草稿只能作者查看
    if story.status == 'draft' and (not request.user.is_authenticated or request.user != story.author):
        return Response({
            'success': False,
            'message': '无权访问该故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 增加浏览量
    story.views += 1
    story.save(update_fields=['views'])
    
    serializer = StoryDetailSerializer(story, context={'request': request})
    
    return Response({
        'success': True,
        'data': serializer.data
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_story(request):
    """创建故事"""
    serializer = StoryCreateSerializer(data=request.data, context={'request': request})
    
    if serializer.is_valid():
        story = serializer.save()
        story_data = StoryDetailSerializer(story, context={'request': request}).data
        
        return Response({
            'success': True,
            'message': '故事保存成功！',
            'data': story_data
        }, status=status.HTTP_201_CREATED)
    
    return Response({
        'success': False,
        'message': '创建失败',
        'errors': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_story(request, story_id):
    """更新故事"""
    story = get_object_or_404(Story, id=story_id)
    
    # 权限检查
    if story.author != request.user and request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '无权限修改其他用户的故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 记录更新前的状态
    old_status = story.status
    
    serializer = StoryCreateSerializer(story, data=request.data, partial=True)
    
    if serializer.is_valid():
        updated_story = serializer.save()
        
        # 如果故事从草稿变为已发布，重置审核状态
        if old_status == 'draft' and updated_story.status == 'published':
            updated_story.review_status = 'pending'
            updated_story.published_at = timezone.now()
            updated_story.save()
        
        story_data = StoryDetailSerializer(updated_story, context={'request': request}).data
        return Response({
            'success': True,
            'message': '故事更新成功！',
            'data': story_data
        })
    
    return Response({
        'success': False,
        'message': '更新失败',
        'errors': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def publish_story(request, story_id):
    """发布故事"""
    story = get_object_or_404(Story, id=story_id)
    
    # 权限检查
    if story.author != request.user:
        return Response({
            'success': False,
            'message': '无权限发布其他用户的故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    story.status = 'published'
    story.published_at = timezone.now()
    
    # 重置审核状态为待审核（允许管理员再次审核）
    story.review_status = 'pending'
    # 清空之前的审核备注（可选，如果想保留历史备注可以注释掉下一行）
    # story.review_note = None
    
    story.save()
    
    return Response({
        'success': True,
        'message': '故事发布成功，等待管理员审核！',
        'data': {
            'id': story.id,
            'status': story.status,
            'review_status': story.review_status,
            'published_at': story.published_at
        }
    })


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_story(request, story_id):
    """删除故事"""
    story = get_object_or_404(Story, id=story_id)
    
    # 权限检查
    if story.author != request.user and request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '无权限删除其他用户的故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    story.delete()
    
    return Response({
        'success': True,
        'message': '故事删除成功！'
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def approve_story(request, story_id):
    """批准故事（管理员）"""
    # 权限检查：只有管理员可以批准
    if request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '只有管理员可以批准故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    story = get_object_or_404(Story, id=story_id)
    
    # 更新审核状态
    story.review_status = 'approved'
    
    # 如果提供了审核备注，保存它
    review_note = request.data.get('review_note')
    if review_note:
        story.review_note = review_note
    
    story.save()
    
    return Response({
        'success': True,
        'message': '故事已批准！',
        'data': {
            'id': story.id,
            'review_status': story.review_status,
            'status': story.status
        }
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def reject_story(request, story_id):
    """驳回故事（管理员）- 将状态改为草稿"""
    # 权限检查：只有管理员可以驳回
    if request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '只有管理员可以驳回故事'
        }, status=status.HTTP_403_FORBIDDEN)
    
    story = get_object_or_404(Story, id=story_id)
    
    # 更新审核状态和故事状态
    story.review_status = 'rejected'
    story.status = 'draft'  # 驳回后改为草稿状态
    
    # 如果提供了审核备注，保存它
    review_note = request.data.get('review_note')
    if review_note:
        story.review_note = review_note
    
    story.save()
    
    return Response({
        'success': True,
        'message': '故事已驳回，状态已改为草稿！',
        'data': {
            'id': story.id,
            'review_status': story.review_status,
            'status': story.status
        }
    })


@api_view(['GET'])
def get_top_stories(request):
    """获取热门故事"""
    limit = int(request.GET.get('limit', 10))
    category = request.GET.get('category')
    
    stories = Story.objects.filter(status='published').select_related('author')
    
    if category:
        stories = stories.filter(category=category)
    
    # 按热度排序（点赞数+浏览量）
    stories = stories.order_by('-likes', '-views')[:limit]
    
    serializer = StoryListSerializer(stories, many=True, context={'request': request})
    
    return Response({
        'success': True,
        'data': serializer.data
    })


@api_view(['GET'])
def get_categories(request):
    """获取所有故事分类"""
    categories = [choice[0] for choice in Story.CATEGORY_CHOICES]
    
    return Response({
        'success': True,
        'data': categories
    })


@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def get_user_stories(request, user_id):
    """获取用户的故事列表"""
    stories = Story.objects.filter(author_id=user_id).select_related('author')
    
    # 草稿只能作者自己看
    if not request.user.is_authenticated or request.user.id != user_id:
        stories = stories.filter(status='published')
    
    status_filter = request.GET.get('status')
    if status_filter:
        stories = stories.filter(status=status_filter)
    
    # 分页
    paginator = PageNumberPagination()
    page = paginator.paginate_queryset(stories, request)
    
    serializer = StoryListSerializer(page, many=True, context={'request': request})
    
    return paginator.get_paginated_response({
        'success': True,
        'data': {
            'items': serializer.data,
            'total': stories.count()
        }
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_analytics(request):
    """获取数据分析统计（管理员）"""
    # 权限检查：只有管理员可以查看
    if request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '只有管理员可以查看数据分析'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 基础统计
    total_users = User.objects.count()
    total_stories = Story.objects.count()
    total_views = sum(story.views for story in Story.objects.all())
    total_likes = sum(story.likes for story in Story.objects.all())
    
    # 故事状态分布
    status_distribution = {
        'published': Story.objects.filter(status='published').count(),
        'draft': Story.objects.filter(status='draft').count(),
    }
    
    # 审核状态分布
    review_distribution = {
        'pending': Story.objects.filter(review_status='pending').count(),
        'approved': Story.objects.filter(review_status='approved').count(),
        'rejected': Story.objects.filter(review_status='rejected').count(),
    }
    
    # 分类分布
    category_distribution = {}
    for category_code, category_name in Story.CATEGORY_CHOICES:
        count = Story.objects.filter(category=category_code).count()
        if count > 0:
            category_distribution[category_name] = count
    
    # 最近7天的故事创建趋势
    today = timezone.now().date()
    daily_stories = []
    for i in range(6, -1, -1):
        date = today - timedelta(days=i)
        count = Story.objects.filter(
            created_at__date=date
        ).count()
        daily_stories.append({
            'date': date.strftime('%m-%d'),
            'count': count
        })
    
    # 最近7天的用户注册趋势
    daily_users = []
    for i in range(6, -1, -1):
        date = today - timedelta(days=i)
        count = User.objects.filter(
            created_at__date=date
        ).count()
        daily_users.append({
            'date': date.strftime('%m-%d'),
            'count': count
        })
    
    # 热门作者（按故事数量）
    top_authors = []
    authors = User.objects.annotate(
        story_count=Count('stories')
    ).filter(story_count__gt=0).order_by('-story_count')[:5]
    
    for author in authors:
        top_authors.append({
            'name': author.name,
            'story_count': author.story_count,
            'total_likes': sum(story.likes for story in Story.objects.filter(author=author))
        })
    
    # 热门故事（按浏览量）
    top_stories = []
    stories = Story.objects.filter(status='published').select_related('author').order_by('-views')[:5]
    for story in stories:
        top_stories.append({
            'id': story.id,
            'title': story.title,
            'author': story.author.name,
            'views': story.views,
            'likes': story.likes
        })
    
    return Response({
        'success': True,
        'data': {
            'overview': {
                'total_users': total_users,
                'total_stories': total_stories,
                'total_views': total_views,
                'total_likes': total_likes
            },
            'status_distribution': status_distribution,
            'review_distribution': review_distribution,
            'category_distribution': category_distribution,
            'daily_stories': daily_stories,
            'daily_users': daily_users,
            'top_authors': top_authors,
            'top_stories': top_stories
        }
    })
